import React, { useState } from "react";
import { Modal, Input, Form, message } from "antd";
import { Button } from "./common/Button";
import { appContext } from "../hooks/provider";
import RegisterModal from "./auth/RegisterModal";

interface SignInModalProps {
  isVisible: boolean;
  onClose: () => void;
  onAuthSuccess: () => void;
}

interface LoginForm {
  username: string;
  password: string;
}

const SignInModal: React.FC<SignInModalProps> = ({ 
  isVisible, 
  onClose, 
  onAuthSuccess 
}) => {
  const { setUser } = React.useContext(appContext);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [showRegister, setShowRegister] = useState(false);

  const handleLogin = async (values: LoginForm) => {
    setLoading(true);
    try {
      const response = await fetch("/api/auth/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username: values.username,
          password: values.password,
        }),
      });

      const data = await response.json();

      if (response.ok && data.status) {
        const tokenData = data.data;
        
        // Store token in localStorage
        localStorage.setItem("access_token", tokenData.access_token);
        localStorage.setItem("token_type", tokenData.token_type);
        
        // Get user info
        const userResponse = await fetch("/api/auth/me", {
          headers: {
            "Authorization": `Bearer ${tokenData.access_token}`,
          },
        });

        if (userResponse.ok) {
          const userData = await userResponse.json();
          if (userData.status) {
            const user = userData.data;
            setUser({
              name: user.full_name || user.username,
              email: user.email || user.username,
              username: user.username,
              metadata: user,
            });
            
            message.success("Login successful!");
            form.resetFields();
            onAuthSuccess();
          }
        }
      } else {
        message.error(data.detail || "Login failed");
      }
    } catch (error) {
      console.error("Login error:", error);
      message.error("Network error. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  const handleSwitchToRegister = () => {
    setShowRegister(true);
  };

  const handleRegisterSuccess = () => {
    setShowRegister(false);
    message.info("Registration successful! Please login with your credentials.");
  };

  const handleRegisterClose = () => {
    setShowRegister(false);
  };

  return (
    <>
      <Modal
        title="Sign In"
        open={isVisible && !showRegister}
        footer={null}
        closable={false}
        maskClosable={false}
        onCancel={onClose}
      >
        <div className="mb-4">
          <p className="text-gray-600">
            Please sign in to access Magentic-UI.
          </p>
        </div>

        <Form
          form={form}
          layout="vertical"
          onFinish={handleLogin}
          requiredMark={false}
        >
          <Form.Item
            name="username"
            label="Username"
            rules={[
              { required: true, message: "Please enter your username" },
            ]}
          >
            <Input placeholder="Enter your username" />
          </Form.Item>

          <Form.Item
            name="password"
            label="Password"
            rules={[
              { required: true, message: "Please enter your password" },
            ]}
          >
            <Input.Password placeholder="Enter your password" />
          </Form.Item>

          <div className="flex flex-col space-y-3">
            <Button
              variant="primary"
              type="submit"
              loading={loading}
              className="w-full"
            >
              Sign In
            </Button>

            <div className="text-center">
              <span className="text-gray-600">Don't have an account? </span>
              <button
                type="button"
                onClick={handleSwitchToRegister}
                className="text-blue-600 hover:text-blue-700 font-medium"
              >
                Register
              </button>
            </div>
          </div>
        </Form>
      </Modal>

      <RegisterModal
        isVisible={showRegister}
        onClose={handleRegisterClose}
        onSuccess={handleRegisterSuccess}
        onSwitchToLogin={() => setShowRegister(false)}
      />
    </>
  );
};

export default SignInModal;
